package com.qianfeng.smartmetting.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qianfeng.smartmetting.authiority.RequirePermission;
import com.qianfeng.smartmetting.entity.Room;
import com.qianfeng.smartmetting.service.RoomDao;
import com.qianfeng.smartmetting.util.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Map;

@RestController
@RequestMapping("/room")
public class RoomController {

    @Autowired
    private RoomDao roomDao;

    //删除单个数据
    @DeleteMapping("/delete/{id}")
    public Map delete(@PathVariable("id") Integer id){
        try{
            boolean flag = roomDao.removeById(id);
            return CommonResult.ok(flag?"删除成功":"删除失败",null);
        }catch (Exception e){
            return CommonResult.error("删除失败");
        }
    }

    @PostMapping("/update")
    public Map modify(@RequestBody Room room){
        try{
//            if (!id.equals(room.getRoomId())){
//                return CommonResult.error(2,"数据异常");
//            }

            boolean flag = roomDao.updateById(room);
            return CommonResult.ok(flag?"修改成功":"修改失败",null);
        }catch (Exception e){
            return CommonResult.error("修改失败");
        }
    }

    @PostMapping("/add")
    public Map add(@RequestBody Room room){
        try{
            boolean flag = roomDao.save(room);
            return CommonResult.ok(flag?"添加成功":"添加失败",null);
        }catch (Exception e){
            return CommonResult.error("服务器异常");
        }
    }

    //一般权限写法
    //用户角色:模块:功能
    //以room模块为例：user:room:list
//    @RequirePermission("user:room:list")
    @GetMapping("/list")
    public Map list(@RequestParam(name="page",defaultValue = "1") Integer page,
                    @RequestParam(name="limit",defaultValue = "10") Integer limit){
        try{
            Page<Room> page1 = new Page<>(page,limit);
            IPage<Room> obj = roomDao.page(page1);
            return CommonResult.ok("查询成功",obj);
        }catch (Exception e){
            return CommonResult.error("发生异常");
        }
    }

    @GetMapping("/get/{id}")
    public Map getById(@PathVariable(name = "id") Integer id){
        try{
            Room room = roomDao.getById(id);
            return CommonResult.ok(room!=null?"查询成功":"该数据不存在",room);
        }catch (Exception e){
            return CommonResult.error("发生异常");
        }
    }

    @DeleteMapping("/delete")
    public Map deleteMore(@RequestBody Long[] ids){
        try{
            boolean flag = roomDao.removeByIds(Arrays.asList(ids));
            return CommonResult.ok(flag?"删除成功":"删除失败",null);
        }catch (Exception e){
            return CommonResult.error("发生异常");
        }
    }
}
